package com.mms.enumerate;

import java.lang.reflect.Field;

/**
 * 枚举的工具
 */
public class EnumTool {

    /**
     * 通过 key 获取 value值
     *
     * @param tClass
     * @param key
     * @param <T>
     * @return
     */
    public static <T> String getValueByKey(Class<T> tClass, int key) {
        T[] enumConstants = tClass.getEnumConstants();
        for (T enumConstant : enumConstants) {
            try {
                Class aClass = enumConstant.getClass();
                Field key1 = aClass.getDeclaredField("key");
                key1.setAccessible(true);
                if ((int) key1.get(enumConstant) == key) {
                    Field value = aClass.getDeclaredField("value");
                    value.setAccessible(true);
                    return (String) value.get(enumConstant);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return null;
    }

    /**
     * 通过 key 获取 枚举对象
     *
     * @param tClass
     * @param key
     * @param <T>
     * @return
     */
    public static <T> T getByKey(Class<T> tClass, int key) {
        T[] enumConstants = tClass.getEnumConstants();
        for (T enumConstant : enumConstants) {
            try {
                Class aClass = enumConstant.getClass();
                Field key1 = aClass.getDeclaredField("key");
                key1.setAccessible(true);
                if ((int) key1.get(enumConstant) == key) {
                    return (T) enumConstant;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return null;
    }

    public static <T> boolean exists(Class<T> tClass, String key) {
        try {
            return exists(tClass, Integer.parseInt(key));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static <T> boolean exists(Class<T> tClass, int key) {
        T[] enumConstants = tClass.getEnumConstants();
        for (T enumConstant : enumConstants) {
            try {
                Class aClass = enumConstant.getClass();
                Field key1 = aClass.getDeclaredField("key");
                key1.setAccessible(true);
                if ((int) key1.get(enumConstant) == key) {
                    return true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return false;
    }
}
